<script setup lang="ts">
import type {
  Datum,
  Enterprise,
  EnterpriseListParams,
  RentBuilding,
  RentParams,
} from "@/types/enterprise";
import {
  createRentAPI,
  delEnterpriseAPI,
  deleteRentAPI,
  getEnterpriseListAPI,
  getRentBuildListAPI,
  getRentListAPI,
  outRentAPI,
} from "@/apis/enterprise";
import { ref, watch } from "vue";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
  type UploadRawFile,
  type UploadRequestOptions,
  type UploadUserFile,
} from "element-plus";
import { uploadAPI } from "@/apis/common";
import AuthBtn from "@/constants/AuthBtn.vue";

// 前端自定义的类型，用于展示嵌套表格
interface EnterpriseWithRent extends Enterprise {
  // 合同列表
  rentList: Datum[];
}

const list = ref<EnterpriseWithRent[]>([]);
const total = ref(0);
const params = ref<EnterpriseListParams>({
  page: 1,
  pageSize: 10,
  name: "", // 企业名称
}); // 表单数据默认值
const initRentForm = () => {
  // 每次调用，都返回一个新对象
  return {
    buildingId: undefined, // 租赁楼宇id
    startTime: "", // 开始日期（不能小于今日日期）
    endTime: "", // 租赁结束日期
    contractUrl: "", // 合同附件url
    contractId: undefined, // 合同附件id
    type: 0, // 操作类型，添加合同0，续签合同1
    enterpriseId: undefined, // 企业id
  };
};

// 表单数据-添加/租赁数据
const rentForm = ref<RentParams>(initRentForm());
// 租赁楼宇的校验规则
const rentRules = ref<FormRules>({
  buildingId: [
    { required: true, message: "请选择租赁楼宇", trigger: "change" },
  ],
  endTime: [{ required: true, message: "请选择租赁日期", trigger: "blur" }],
  contractId: [{ required: true, message: "请上传租赁合同" }],
});

const getList = async () => {
  const res = await getEnterpriseListAPI(params.value);
  // console.log("res", res);
  list.value = res.data.rows.map((item) => ({
    ...item,
    rentList: [], // 合同列表默认值
  }));
  total.value = res.data.total;
};
getList();

const onSearch = () => {
  // 重置页码
  params.value.page = 1;
  getList();
};

// 删除企业
const delPrise = (id: string) => {
  ElMessageBox.confirm("此操作将永久删除该企业, 是否继续?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await delEnterpriseAPI([id]);
      ElMessage.success("删除成功");
      getList();
    })
    .catch(() => {});
};

// ----------------
// 添加合同
const rentDialogVisible = ref(false);

const buildList = ref<RentBuilding[]>([]);
// 点击添加，打开弹窗
const addRent = async (id: number) => {
  rentDialogVisible.value = true;
  const res = await getRentBuildListAPI();
  // console.log('res',res)
  buildList.value = res.data;
  rentForm.value.enterpriseId = id;
};
// 点击确定，添加合同
const addRentConfirm = async () => {
  try {
    // 1. 校验表单
    await addFormRef.value?.validate();
    // 2. 提交表单数据给后端
    await createRentAPI(rentForm.value);
    // 3.请提示
    ElMessage.success("添加成功");
    // 4.关闭弹窗
    rentDialogVisible.value = false;
  } catch {}
};

const fileList = ref<UploadUserFile[]>([]);
// 点击取消，关闭
const closeRent = () => {
  rentDialogVisible.value = false;
  // 清空表单校验
  addFormRef.value?.resetFields();
  // 清空数组表单
  timeArr.value = [];

  fileList.value = [];
  // 重置表单数据
  rentForm.value = initRentForm();
};

// 时间选择器-侦听时间
const timeArr = ref<string[]>([]);
watch(
  timeArr,
  (val) => {
    if (val) {
      rentForm.value.startTime = val[0];
      rentForm.value.endTime = val[1];
    } else {
      rentForm.value.startTime = "";
      rentForm.value.endTime = "";
    }
  },
  { deep: true }
);
// 通过disableDate函数，来设置禁用的日期
const disableDate = (time: Date) => {
  // 不能小于今日日期，包含今天
  return time.getTime() < Date.now() - 1000 * 60 * 60 * 24;
};

const addFormRef = ref<FormInstance>();
// 上传文件
const onUploadRequest = async (options: UploadRequestOptions) => {
  console.log(options);
  const fd = new FormData();
  fd.append("file", options.file); // 文件对象
  fd.append("type", "contract"); // 上传类型

  const res = await uploadAPI(fd);

  // 保存合同附件
  rentForm.value.contractId = res.data.id;
  rentForm.value.contractUrl = res.data.url;
  addFormRef.value?.validateField("contractUrl");

  return res.data;
};
// 删除文件时
const removeUpload = () => {
  rentForm.value.contractId = undefined;
  rentForm.value.contractUrl = "";
  addFormRef.value?.validateField("contractId");
};

// 上传文件校验大小
const beforUpload = (rawFile: UploadRawFile) => {
  console.log(rawFile.type);
  const allowSize = 1024;
  if (rawFile.size > allowSize) {
    ElMessage.error("上传文件不能超过5M");
    return false;
  }
  return true;
};

// 展开行时触发
const onExpandChange = async (row: EnterpriseWithRent) => {
  // 获取企业的合同列表
  const res = await getRentListAPI(row.id);
  console.log("当前行被展开", row.id);
  row.rentList = res.data;
};

// 删除合同
const outRent = async (row: Datum) => {
  ElMessageBox.confirm("确定删除该合同吗？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      // console.log(id)
      await outRentAPI(row.id);
      row.status = 3;
      ElMessage.success("删除成功");
    })
    .catch(() => {
      ElMessage.success("取消删除");
    });
};

// 删除合同
const deleteRent = async (sonRow: Datum, fatherRow: EnterpriseWithRent) => {
  ElMessageBox.confirm("确定删除该合同吗？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      // 发送请求，更新后端合同状态(后端)
      await deleteRentAPI(sonRow.id);
      // 删除过滤合同(前端)
      fatherRow.rentList = fatherRow.rentList.filter(
        (item) => item.id !== sonRow.id
      );
      // 轻提示
      ElMessage.success("删除成功");
    })
    .catch(() => {});
};
</script>

<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input
        clearable
        placeholder="请输入内容"
        class="search-main"
        v-model="params.name"
        @clear="onSearch"
      />
      <el-button type="primary" @click="onSearch">查询</el-button>
    </div>
    <div class="create-container">
      <el-button @click="$router.push('/exterpriseAdd')" type="primary"
        >添加企业</el-button
      >
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <!-- @expand-change 展开或折叠行时触发 -->
      <el-table
        style="width: 100%"
        :data="list"
        @expand-change="onExpandChange"
        row-key="id"
      >
        <!-- type="expand" 显示一个可展开的按钮 -->
        <el-table-column type="expand">
          <template #default="{ row }">
            <el-table :data="row.rentList">
              <el-table-column
                label="租赁楼宇"
                width="320"
                prop="buildingName"
              />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态" prop="status">
                <!-- 合同的租赁状态 0待生效 1生效中 2已到期 3已退租 -->
                <template v-slot="{ row }">
                  <el-tag v-if="row.status === 0" type="warning">待生效</el-tag>
                  <el-tag v-else-if="row.status === 1" type="success"
                    >生效中</el-tag
                  >
                  <el-tag v-else-if="row.status === 2" type="info"
                    >已到期</el-tag
                  >
                  <el-tag v-else-if="row.status === 3" type="danger"
                    >已退租</el-tag
                  >
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template v-slot="{ row: rentRow }">
                  <el-button size="small" type="primary" link>续租</el-button>
                  <el-button
                    size="small"
                    @click="outRent(rentRow)"
                    type="primary"
                    link
                    :disabled="rentRow.status === 3"
                    >退租</el-button
                  >
                  <el-button
                    size="small"
                    @click="deleteRent(rentRow, row)"
                    type="primary"
                    link
                    :disabled="rentRow.status !== 3"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="120" />
        <el-table-column prop="name" label="企业名称" width="320" />
        <el-table-column prop="contact" label="联系人" />
        <el-table-column prop="contactNumber" label="联系电话" />
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <AuthBtn btn-perm="park:rent:add_surrender">
              <el-button size="small" type="primary" link @click="addRent(row.id)"
              >添加合同</el-button
            >
            </AuthBtn>
            <el-button
              size="small"
              type="primary"
              link
              @click="$router.push(`/exterpriseDetail/${row.id}`)"
              >查看</el-button
            >
            <el-button
              size="small"
              type="primary"
              link
              @click="$router.push(`/exterpriseAdd/${row.id}`)"
              >编辑</el-button
            >
            <AuthBtn btn-perm="park:enterprise:remove">
              <el-button
              size="small"
              type="primary"
              link
              @click="delPrise(row.id)"
              >删除</el-button
            >
            </AuthBtn>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        :total="total"
        layout="total,sizes, prev, pager, next,jumper"
        :page-sizes="[2, 5, 10, 20]"
        v-model:page-size="params.pageSize"
        v-model:current-page="params.page"
        @change="getList()"
      />
    </div>
    <el-dialog
      v-model="rentDialogVisible"
      width="580"
      title="添加合同"
      @close="closeRent"
    >
      <!-- 表单模版 -->
      <div class="form-container">
        <el-form
          ref="addFormRef"
          :model="rentForm"
          :rules="rentRules"
          label-position="top"
        >
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select
              v-model="rentForm.buildingId"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in buildList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="endTime">
            <el-date-picker
              v-model="timeArr"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              :disabled-date="disableDate"
            />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload
              v-model:file-list="fileList"
              accept=".doc, .pdf"
              :http-request="onUploadRequest"
              @remove="removeUpload"
              :before-upload="beforUpload"
            >
              <el-button size="small" type="primary" plain
                >上传合同文件</el-button
              >
              <template #tip>
                <div class="el-upload__tip">
                  支持扩展名：.doc .pdf, 文件大小不超过5M
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      {{ timeArr }}
      {{ rentForm }}
      <template #footer>
        <el-button @click="closeRent">取消</el-button>
        <el-button @click="addRentConfirm" type="primary">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>
